package org.jash.imdemo.fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.hyphenate.chat.EMConversation;

import org.jash.imdemo.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

public class ConversationAdapter extends RecyclerView.Adapter<ConversationAdapter.ConversationViewHolder> {
    private List<EMConversation> data = new ArrayList<>();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    private OnConversationClickListener listener;
    public ConversationAdapter() {
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
    }

    @NonNull
    @Override
    public ConversationViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ConversationViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_conversation, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ConversationViewHolder holder, int position) {
        EMConversation conversation = data.get(position);
        holder.username.setText(conversation.conversationId());
        holder.lastDate.setText(sdf.format(new Date(conversation.getLastMessage().getMsgTime())));
        int count = conversation.getUnreadMsgCount();
        if (count == 0) {
            holder.unread.setVisibility(View.GONE);
        } else {
            holder.unread.setVisibility(View.VISIBLE);
            holder.unread.setText("" + count);
        }
        if (listener != null) {
            holder.itemView.setOnClickListener(v -> listener.onConversationClick(conversation));
        }

    }

    public void setListener(OnConversationClickListener listener) {
        this.listener = listener;
    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    public void addAll(Collection<? extends EMConversation> collection) {
        int size = data.size();
        data.addAll(collection);
        notifyItemRangeInserted(size, collection.size());
    }

    public interface OnConversationClickListener {
        void onConversationClick(EMConversation conversation);
    }
    public static class ConversationViewHolder extends RecyclerView.ViewHolder {
        private TextView username, lastDate, unread;
        public ConversationViewHolder(@NonNull View itemView) {
            super(itemView);
            username = itemView.findViewById(R.id.username);
            lastDate = itemView.findViewById(R.id.last_date);
            unread = itemView.findViewById(R.id.unread);
        }
    }

}
